package org.idea.spring.jdbc.xa;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.StatementImpl;

import javax.sql.DataSource;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author linhao
 * @Date created in 10:56 上午 2021/11/4
 */
public class DruidTimeOutDemo {


    public static String driver = "com.mysql.jdbc.Driver";
    public static String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&connectTimeout=60000&socketTimeout=60000";
    public static String username = "root";
    public static String password = "root";
    public static String sql = "SELECT * from CrmMessage where memberId like '%123%' and content like '1xopas%' order by id desc ";


    public static void main(String[] args) throws SQLException {
        DataSource dataSource = getDataSource();
        StatementImpl statement = new StatementImpl();
        statement.cancel();
        DruidPooledConnection druidPooledConnection = (DruidPooledConnection) dataSource.getConnection();//进行链接(2)
        PreparedStatement preparedStatement = druidPooledConnection.prepareStatement(sql);
        long startTime = System.currentTimeMillis();
        ResultSet rs = preparedStatement.executeQuery();
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime +"ms");
//        while (rs.next()) {
//            int i = rs.getInt(1);
//            System.out.println(i);
//        }
        druidPooledConnection.close();
    }

    public static DataSource getDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setPassword(password);
        //具体配置
        druidDataSource.setMaxActive(50);
        druidDataSource.setInitialSize(3);
        druidDataSource.setMinIdle(1);
        druidDataSource.setQueryTimeout(300);
        druidDataSource.setMaxWait(30000);
        druidDataSource.setTestWhileIdle(true);
        druidDataSource.setFailFast(true);
        druidDataSource.setMinEvictableIdleTimeMillis(300000);
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.setTestOnReturn(false);
        druidDataSource.setValidationQuery("select 1");
        //间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        druidDataSource.setTimeBetweenConnectErrorMillis(60000);
        return druidDataSource;
    }
}
